package com.dhcc.sdc.busi.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.base.entity.SdcQcCdssLinkEntity;
import com.dhcc.sdc.base.service.ISdcQcCdssLinkService;
import com.dhcc.sdc.busi.entity.SdcQcEntity;
import com.dhcc.sdc.busi.entity.SdcQcRuleDatasourceEntity;
import com.dhcc.sdc.busi.service.ISdcQcRuleDatasourceService;
import com.dhcc.sdc.busi.service.ISdcQcService;
import com.dhcc.sdc.base.service.ICdssStandardMatchService;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.standard.service.ISdsStandRuleBaseService;
import com.dhcc.sds.standard.service.ISdsStandSourceFieldService;
import com.dhcc.sds.standard.service.ISdsStandSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 单病种质控配置
 *
 * @ClassName: SdcQcConfigController
 * @Description: TODO
 * @author zhangdc
 * @date 2022-07-26 14:24:20
 */
@Controller
@RequestMapping("${sys.backendPath}/sdc/sdcqcconfig")
public class SdcQcConfigController extends BaseController {

    private String PREFIX = "/backend/sdc/sdcqcconfig/";

    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdcQcService sdcQcService;
    @Autowired
    private ICdssStandardMatchService cdssStandardMatchService;
    @Autowired
    private ISdcQcRuleDatasourceService sdcQcRuleDatasourceService;
    @Autowired
    private ISdsStandSourceService sdsStandSourceService;
    @Autowired
    private ISdsStandSourceFieldService sdsStandSourceFieldService;
    @Autowired
    private ISdcQcCdssLinkService sdcQcCdssLinkService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Resource
    private ISdsStandRuleBaseService sdsRuleBaseService;

    /**
     * 跳转到单病种质控配置首页
     */
    @RequestMapping("")
    public String index(Model model) {

        //获取病种
        JSONArray entityMap = sdsQcentityService.getEntityMap2();
//        JSONArray entityMap = sdsCommonService.getEntityMap();
        //获取诊疗方案
        //JSONArray cdssMap = cdssStandardMatchService.findCdssList();
        model.addAttribute("entityMap",entityMap);
        //model.addAttribute("cdssMap",cdssMap);
        return PREFIX + "sdcqcconfig.html";
    }

    /**
     * 根据病种id查询质控条目
     */
    @RequestMapping(value = "/selectQcByEntityId")
    @ResponseBody
    public Object selectQcByEntityId(@RequestParam Map<String, Object> params) {
        return sdcQcService.list(params);
    }

    @RequestMapping(value = "/edit")
    @ResponseBody
    public Object edit(SdcQcEntity sdcQcEntity) {
        if (CommonUtil.isOneEmpty(sdcQcEntity)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            // 这5个因为前台需要输入特殊字符，前台已转码，因此后台也需要转码
            sdcQcEntity.setQcDesc(java.net.URLDecoder.decode(sdcQcEntity.getQcDesc(), "UTF-8"));
            sdcQcEntity.setQcExpression(java.net.URLDecoder.decode(sdcQcEntity.getQcExpression(), "UTF-8"));
            sdcQcEntity.setQcMemo(java.net.URLDecoder.decode(sdcQcEntity.getQcMemo(), "UTF-8"));
            sdcQcEntity.setExpDescription(java.net.URLDecoder.decode(sdcQcEntity.getExpDescription(), "UTF-8"));
            sdcQcEntity.setSource(java.net.URLDecoder.decode(sdcQcEntity.getSource(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (CommonUtil.isEmpty(sdcQcEntity.getId())) {
            sdcQcEntity.insert();
            if (!StringUtils.isEmpty(sdcQcEntity.getLinkCdss())){
                String[] split = sdcQcEntity.getLinkCdss().split("#");
                for (String s : split){
                    if (!StringUtils.isEmpty(s)){
                        SdcQcCdssLinkEntity sdcQcCdssLinkEntity = new SdcQcCdssLinkEntity();
                        sdcQcCdssLinkEntity.setQcItemId(sdcQcEntity.getId());
                        sdcQcCdssLinkEntity.setCdssNodeId(s);
                        sdcQcCdssLinkEntity.insert();
                    }
                }
            }
        } else {
            SdcQcEntity sdcQcEntity1 = sdcQcService.selectById(sdcQcEntity.getId());
            sdcQcEntity1.setQcMemo(sdcQcEntity.getQcMemo());
            sdcQcEntity1.setQcExpression(sdcQcEntity.getQcExpression());
            sdcQcEntity1.setQcDesc(sdcQcEntity.getQcDesc());
            sdcQcEntity1.setExpDescription(sdcQcEntity.getExpDescription());
            sdcQcEntity1.setActiveOnce(sdcQcEntity.getActiveOnce());
            sdcQcEntity1.setIsActive(sdcQcEntity.getIsActive());
            sdcQcEntity1.setType(sdcQcEntity.getType());
            sdcQcEntity1.setSource(sdcQcEntity.getSource());
            sdcQcEntity1.setIsBox(sdcQcEntity.getIsBox());
            //sdcQcEntity1.setLinkCdss(sdcQcEntity.getLinkCdss());
            sdcQcEntity1.updateAllColumnById();

            if (!StringUtils.isEmpty(sdcQcEntity.getLinkCdss())){
                List<SdcQcCdssLinkEntity> qcCdssLinkEntities = sdcQcCdssLinkService.selectList(new EntityWrapper<SdcQcCdssLinkEntity>()
                        .eq("qc_item_id", sdcQcEntity.getId()));
                if (!qcCdssLinkEntities.isEmpty()){
                    sdcQcCdssLinkService.deleteByQcItemId(sdcQcEntity.getId());
                }
                String[] split = sdcQcEntity.getLinkCdss().split("#");
                for (String s : split){
                    if (!StringUtils.isEmpty(s)){
                        SdcQcCdssLinkEntity sdcQcCdssLinkEntity = new SdcQcCdssLinkEntity();
                        sdcQcCdssLinkEntity.setQcItemId(sdcQcEntity.getId());
                        sdcQcCdssLinkEntity.setCdssNodeId(s);
                        sdcQcCdssLinkEntity.insert();
                    }
                }
            }else {
                //删除之前的关系
                List<SdcQcCdssLinkEntity> qcCdssLinkEntities = sdcQcCdssLinkService.selectList(new EntityWrapper<SdcQcCdssLinkEntity>()
                        .eq("qc_item_id", sdcQcEntity.getId()));
                if (!qcCdssLinkEntities.isEmpty()){
                    sdcQcCdssLinkService.deleteByQcItemId(sdcQcEntity.getId());
                }
            }

        }
        return R.ok();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long qcId) {
        this.sdcQcService.deleteById(qcId);
        return R.ok();
    }

    /**
     *
     */
    @RequestMapping(value = "/selectQcRuleByExpression")
    @ResponseBody
    public Object selectQcRuleByExpression(@RequestParam Map<String, Object> params) {
//        return sdcQcRuleService.selectByExpression(params);
        return sdsRuleBaseService.selectDisplayRule(params);
    }

    @RequestMapping(value = "/selectQcRuleDataSourceByExpression")
    @ResponseBody
    public Object selectQcRuleDataSourceByExpression(@RequestParam Map<String, Object> params) {
        return sdcQcRuleDatasourceService.selectByExpression(params);
    }

    @RequestMapping("/to_addRule")
    public String to_addRule(Model model) {
        //JSONObject dataSourceMap = sdcQcRuleDatasourceService.getDataSourceMap();
        JSONObject standSourceMap = sdsStandSourceService.getSourceMap();
        //JSONObject dataSourceItemMap = sdcQcRuleDatasourceService.getDataSourceItemMap();
        model.addAttribute("dataSourceMap",standSourceMap);
        //model.addAttribute("dataSourceItemMap",dataSourceItemMap);
        return PREFIX + "sdcqcrule_add.html";
    }

    @RequestMapping("/to_updateRule/{sdcQcRuleId}")
    public String toUpdate(@PathVariable Long sdcQcRuleId, Model model) {
        //SdcQcRuleEntity sdcQcRule = this.sdcQcRuleService.selectById(sdcQcRuleId);
        JSONObject standSourceMap = sdsStandSourceService.getSourceMap();
        /*JSONArray standSourceMap = sdsStandSourceService.getSourceArrayMap();*/
        //model.addAttribute("sdcQcRule",JSONObject.toJSON(sdcQcRule));
        model.addAttribute("dataSourceMap",standSourceMap);
        model.addAttribute("sdcQcRuleId",sdcQcRuleId);
        return PREFIX + "sdcqcrule_edit.html";
    }

    @RequestMapping("/to_addRuleSource")
    public String to_addRuleSource() {
        return PREFIX + "sdcqcruledatasource_add.html";
    }

    @RequestMapping(value = "/addRuleSource")
    @ResponseBody
    public Object addRuleSource(SdcQcRuleDatasourceEntity sdcQcRuleDatasource) {
        if (CommonUtil.isOneEmpty(sdcQcRuleDatasource)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        sdcQcRuleDatasource.insert();
        return R.ok();
    }

    @RequestMapping("/to_updateRuleSource/{sdcQcRuleDatasourceId}")
    public String to_updateRuleSource(@PathVariable Long sdcQcRuleDatasourceId, Model model) {
        SdcQcRuleDatasourceEntity sdcQcRuleDatasource = this.sdcQcRuleDatasourceService.selectById(sdcQcRuleDatasourceId);
        model.addAttribute("sdcQcRuleDatasource",sdcQcRuleDatasource);
        return PREFIX + "sdcqcruledatasource_edit.html";
    }

    @RequestMapping(value = "/updateRuleSource")
    @ResponseBody
    public Object updateRuleSource(SdcQcRuleDatasourceEntity sdcQcRuleDatasource) {
        if (CommonUtil.isOneEmpty(sdcQcRuleDatasource)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdcQcRuleDatasourceEntity old = this.sdcQcRuleDatasourceService.selectById(sdcQcRuleDatasource.getId());

        old.setCode(sdcQcRuleDatasource.getCode());
        old.setDataSource(sdcQcRuleDatasource.getDataSource());
        old.setDataSourceItem(sdcQcRuleDatasource.getDataSourceItem());
        old.setHavePar(sdcQcRuleDatasource.getHavePar());
        old.updateAllColumnById();
        return R.ok();
    }

    @RequestMapping(value = "/cancelRuleSource")
    @ResponseBody
    public Object cancelRuleSource(@RequestParam Long sdcQcRuleDatasourceId) {

        this.sdcQcRuleDatasourceService.deleteById(sdcQcRuleDatasourceId);

        return R.ok();
    }

    @RequestMapping("/to_import")
    public String toImport() {
        return PREFIX + "import.html";
    }

    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    public R importItem(@RequestPart("file") MultipartFile file) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream(),0);
            List<List<Object>> qcAll = reader.read();
            this.sdcQcService.importItem(qcAll);
//            reader = ExcelUtil.getReader(file.getInputStream(),1);
//            List<List<Object>> ruleAll = reader.read();
//            this.sdcQcRuleService.importItem(ruleAll);
//            reader = ExcelUtil.getReader(file.getInputStream(),2);
//            List<List<Object>> datasourceAll = reader.read();
            //this.sdcQcRuleDatasourceService.importItem(datasourceAll);
//            this.sdsStandSourceFieldService.importEntities(datasourceAll);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @RequestMapping("/getCdssMapByEntityId")
    @ResponseBody
    public Object getCdssMapByEntityId(@RequestParam Map<String, Object> params){
        String entityId = (String) params.get("entityId");
        return this.cdssStandardMatchService.findCdssList(Long.parseLong(entityId));
    }


    @RequestMapping("/getByEntityId")
    @ResponseBody
    public Object getByEntityId(@RequestParam Map<String, Object> params){
        String entityId = (String) params.get("entityId");
        return this.sdcQcService.getJSONArrayByEntityId(Long.parseLong(entityId));
    }

}
